package fplaton.db;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author dastergon
 */
public class SQLiteJDBC {

    private final String Url;
    private final String DriverName;
    private String Driver;
    public Connection conn;
    public Statement stmt;

    public SQLiteJDBC(String DbUrl) {
        this.Url = "jdbc:sqlite:" + DbUrl;
        this.DriverName = "org.sqlite.JDBC";
        this.conn = null;
        this.stmt = null;

        try {
            setConnection(); // create a connection to the DB
        } catch (Exception ex) {
            Logger.getLogger(SQLiteJDBC.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void setConnection() throws Exception {
        try {
            Class.forName(DriverName);
        } catch (ClassNotFoundException e) {
            // connection failed.
            System.out.println("DriverName: " + Driver
                    + " was not available");
            System.err.println(e);
            throw e;
        }
        // create a database connection
        conn = DriverManager.getConnection(Url);
        try {
            stmt = conn.createStatement();
        } catch (SQLException e) {
            try {
                conn.close();
            } catch (SQLException ignore) {
            }
            conn = null;
        }
    }

    public void closeConnection() {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ignore) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ignore) {
            }
        }
    }

    public ResultSet executeQuery(String instruction) throws SQLException {
        return stmt.executeQuery(instruction);
    }

    public void execute(String instruction) throws SQLException {
        stmt.executeUpdate(instruction);
    }

}
